import React from "react";
import SearchHeader from "./component/SearchHeader";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import "../style/style.less";
import ThePagination from "../../../components/ThePagination";
import TheImage from '@/components/TheImage'
import TheDialog from '@/components/TheDialog'
import SkuChange from './component/SkuDetailsChange'
import _ from 'lodash'
import { apiGetGoodsInfoPage, apiGetGoodsInfoDel, apiGetGoodsInfoPutway, apiUpdateInventory, getAllGoodsDetail } from '@/request/mallManagement'
import { apiGetCalssify } from '@/request/commodity'
import { Space, List, Modal } from "antd";
import { exportSheetTable, } from '@/utils/exportTable'
class MallList extends React.Component {
  state = {
    down_loading: false,
    columns: [
      {
        title: "商品ID",
        dataIndex: "goodsId",
        key: "goodsId",
      },
      {
        title: "商品名称",
        dataIndex: "goodsName",
        key: "goodsName",
      },
      {
        title: "商品图片",
        dataIndex: "goodsShowImages",
        key: "goodsShowImages",
        render: (text, record) => {
          let arr = text.split(',')
          return <Space>
            {
              arr.map(v => {
                return <TheImage src={v} width={80} height={80} />
              })
            }
          </Space>
        }
      },
      {
        title: "所属类目",
        dataIndex: "goodsClassifyName",
        key: "goodsClassifyName",
      },
      {
        title: "商品原价",
        dataIndex: "originalPrice",
        key: "originalPrice",
        render: (text, record) => {
          return <React.$Price price={record.originalPrice || 0} />
        }
      },
      {
        title: "商品现价",
        dataIndex: "currentPrice",
        key: "currentPrice",
        render: (text, record) => {
          return <React.$Price price={record.currentPrice || 0} />
        }
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
      },
      {
        title: "申请时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "上次操作时间",
        dataIndex: "lastUpdateTime",
        key: "lastUpdateTime",
        render: (text, record) => {
          return record.lastUpdateTime ? record.lastUpdateTime : "/"
        }
      },
      {
        title: "操作人",
        dataIndex: "userName",
        key: "userName",
        render: (text, record) => {
          return record.userName ? record.userName : "/"
        }
      },
      {
        title: "状态",
        dataIndex: "goodsStatus",
        key: "goodsStatus",
        render: (text, render) => {
          let label = ''
          switch (render.goodsStatus) {
            case 'Y':
              label = "上架"
              break;
            case 'N':
              label = "下架"
              break;
            case 'G':
              label = '管理员下架'
              break;
            default:
              label = "字段值错误"
          }
          return label
        }
      },
      {
        title: "操作",
        fixed: "right",
        width: 300,
        render: (text, render) => {
          return (
            <div>
              {/* <TheButton  hasPermi={['mall:list:synchronization']} onClick={() => this.openSynchronousDialog(render.goodsId)}>同步商品至门店</TheButton> */}
              <TheButton hasPermi={['mall:centerlist:batchSynchronization']} onClick={() => this.openSynchronousDialog(render.goodsId)} disabled={render.whetherSyn === 0 ? false : true}  >同步商品至商城</TheButton>
              <TheButton hasPermi={['mall:centerlist:detail']} onClick={() => this.goDetail(render.goodsId)}>商品详情</TheButton>
              <TheButton hasPermi={['mall:centerlist:edit']} onClick={() => this.goEdit(render.goodsId)}>修改商品</TheButton>
              <TheButton hasPermi={['mall:centerlist:evaluate']} onClick={() => this.goEvaluate(render.goodsId, render.storeName)}>商品评价</TheButton>
              {/* <TheButton hasPermi={['mall:list:delete']} onClick={() => this.delConfirm(render.goodsId)}>删除商品</TheButton> */}
              {/* {(render.goodsStatus === 'N' && render.goodsStatus !== 'G') && <TheButton hasPermi={['mall:list:onShelf']} onClick={() => this.putShelf(render.goodsId, 'Y')}>上架</TheButton>}
              {render.goodsStatus === 'Y' && <TheButton hasPermi={['mall:list:onShelf']} onClick={() => this.offShelf(render.goodsId, 'N')}>下架</TheButton>} */}
              {/* <TheButton hasPermi={['mall:list:updateStock']} onClick={() => this.openSkuDialog(render.goodsId)}>修改库存</TheButton> */}
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    searchValue: {},
    loading: false,
    options: null,
    synchronousLoading: false,
    checked: [],
    ErrSyncVisible: false,
    syncfail: [],
    modalvisible: false,
    goods: "",
  };
  async componentDidMount() {
    if (localStorage.getItem('searchValue') && localStorage.getItem('pageNo')) {
      let search = JSON.parse(localStorage.getItem('searchValue'))
      this.setState({
        searchValue: search,
        pageData: {
          pageNo: localStorage.getItem('pageNo'),
          pageSize: 10
        }
      }, async () => {
        await this.getData()
        await this.getClassifyList()
      })
    } else if (localStorage.getItem('pageNo')) {
      this.setState({
        pageData: {
          pageNo: localStorage.getItem('pageNo'),
          pageSize: 10
        }
      }, async () => {
        await this.getData()
        await this.getClassifyList()
      })
    } else {
      await this.getData()
      await this.getClassifyList()
    }

  }
  getClassifyList = async () => {
    let res = await apiGetCalssify()
    let options = res.data.map(v => {
      return {
        label: v.productClassifyName,
        value: v.productClassifyId
      }
    })
    this.setState({
      options
    })
  }
  openSynchronousDialog = async (goodsId) => {
    this.setState({
      synchronousVisible: true,
      synchronousGoodsId: goodsId
    })
  }
  closeSynchronousDialog = () => {
    this.setState({
      synchronousVisible: false,
      synchronousGoodsId: ''
    })
  }
  closeSyncDialog = () => {
    this.setState({
      syncVisible: false,
      // checked: []
    })
  }
  synchronousSave = async () => {
    this.setState({
      synchronousLoading: true
    })
    console.log(this.state.synchronousGoodsId);
    let params = this.state.synchronousGoodsId
    React.$post('/management/storeGoods/synStoreGoodsByGoodsId', { goodsIds: params }).then(res => {
      if (res.code === 0) {
        // if(res.data.length > 0){
        //   React.$message({
        //     type: 'info',
        //     content: '该商品已同步，请勿重复操作！'
        //   })
        //   this.closeSynchronousDialog()
        //   this.getData()
        //   this.setState({
        //     synchronousLoading:false,
        //     rowSelection :{
        //       onChange: (record,selected )=>{
        //         this.onChange(record.goodsId,selected)
        //       },
        //       onChangeAll: (selected,  changeRows) => {
        //         const allId = changeRows.map((item) => {
        //           return item.goodsId;
        //         });
        //         this.onCheckedBoxAll(allId, selected);
        //       },
        //     },
        //   })
        // }else{
        React.$message({
          type: 'info',
          content: '同步成功，请在商品库中补全商品信息'
        })
        this.closeSynchronousDialog()
        this.getData()
        this.setState({
          synchronousLoading: false,
          rowSelection: {
            onChange: (record, selected) => {
              this.onChange(record.goodsId, selected)
            },
            onChangeAll: (selected, changeRows) => {
              const allId = changeRows.map((item) => {
                return item.goodsId;
              });
              this.onCheckedBoxAll(allId, selected);
            },
          },
        })
        // }
      } else {
        this.closeSynchronousDialog()
        this.getData()
        this.setState({
          synchronousLoading: false,
          rowSelection: {
            onChange: (record, selected) => {
              this.onChange(record.goodsId, selected)
            },
            onChangeAll: (selected, changeRows) => {
              const allId = changeRows.map((item) => {
                return item.goodsId;
              });
              this.onCheckedBoxAll(allId, selected);
            },
          },
        })
      }
    })
  }
  syncSave = async () => {
    this.setState({
      synchronousLoading: true
    })
    // let goodsIdArr = this.state.checked
    // console.log(goodsIdArr);
    // return
    // let goodsIdArr = {goodsId: this.state.checked}
    // let params = {
    //   ...goodsIdArr
    // }
    React.$post('/management/storeGoods/synStoreGoodsByGoodsId', { goodsIds: this.state.checked }).then(res => {
      if (res.code === 0) {
        // if(res.data.length > 0){
        //   this.closeSyncDialog()
        //   let errdata = []
        //   for(let i=0; i<res.data.length; i++){
        //     errdata = errdata.concat({
        //       title:res.data[i]
        //     })
        //   }
        //   console.log(errdata)

        //   this.setState({
        //     synchronousLoading:false,
        //     selectedRows: [],
        //     selectedRowKeys: [],
        //     ErrSyncVisible:true,
        //     syncfail:errdata
        //   })
        //   this.getData()
        //   React.$message({
        //     type: 'info',
        //     content: '同步成功，请在商品库中补全商品信息'
        //   })
        // }else{
        this.closeSyncDialog()
        this.setState({
          synchronousLoading: false,
          selectedRows: [],
          selectedRowKeys: []
        })
        this.getData()
        React.$message({
          type: 'info',
          content: '同步成功，请在商品库中补全商品信息'
        })
        // }
      } else {
        this.closeSyncDialog()
        this.setState({
          synchronousLoading: false,
          selectedRows: [],
          selectedRowKeys: []
        })
        this.getData()
      }
    })
  }
  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let res = await apiGetGoodsInfoPage({ ...pageData, ...searchValue, reviewStatus: 'T' })
    if (res.code === 0 && res.data) {
      this.setState({ dataSource: res.data, pageData: { pageNo: res.pageNo, pageSize: res.pageSize }, total: res.totalCount, loading: false })
    }
  }
  getValue = (value) => {
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => {
      this.getData()
      let search = JSON.stringify(this.state.searchValue)
      localStorage.setItem('searchValue', search)
      localStorage.setItem('pageNo', this.state.pageData.pageNo)
    })
  }
  goDetail = (goodsId) => {
    this.props.history.push(`/mall/list/detail/${goodsId}`);
  };
  goEvaluate = (goodsId, storeName) => {
    this.props.history.push(`/mall/list/evaluate/${goodsId}/${encodeURIComponent(storeName)}`);
  };
  goEdit = async (goodsId) => {
    let res = await React.$post("/management/goodsInfo/whetherCutPriceGoods", { GoodsId: goodsId })
    if (res.code === 0 && res.data) {
      this.setState({ modalvisible: true, goods: goodsId })
    } else {
      this.props.history.push(`/mall/list/edit/${goodsId}`);
    }
  }
  onOk = () => {
    let goodsId = this.state.goods
    this.setState({ modalvisible: false })
    this.props.history.push(`/mall/list/edit/${goodsId}`);
  }
  onCancel = () => {
    this.setState({ modalvisible: false, goods: "" })
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      },
      selectedRows: [],
      selectedRowKeys: []
    }, () => {
      localStorage.setItem('pageNo', this.state.pageData.pageNo);
      this.getData()
    })
  };
  onChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRows: selectedRows,
      selectedRowKeys: selectedRowKeys
    }, () => {
      let rows = this.state.selectedRows.length
      let goods = ""
      for (let i = 0; i < rows; i++) {
        goods += selectedRows[i].goodsId + ","
      }
      this.setState({
        checked: goods
      })
    })

    // console.log(this.state.selectedRows, '....',this.state.selectedRowKeys)
    // let goodsid = selected ? _.concat(this.state.checked,e) : _.difference(this.state.checked,[e])
    // // console.log(goodsid)
    // this.setState({
    //   checked: [...goodsid]
    // },()=>{
    //   // console.log(this.state.checked)
    // })

  }
  pushSync() {
    let checklen = this.state.checked.length
    if (checklen === 0) {
      React.$message({
        type: 'info',
        content: '请先勾选商品'
      })
    } else {
      this.setState({
        syncVisible: true
      })
    }
    // console.log(this.state.checked)
  }
  delConfirm = (goodsId) => {
    React.$confirm({
      title: "您确认删除此条商品吗?",
      onOk: async () => {
        let res = await apiGetGoodsInfoDel({ goodsId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      },
    });
  };
  offShelf = (goodsId, goodsStatus) => {
    React.$confirm({
      title: '您确定下架该商品吗？',
      onOk: async () => {
        await apiGetGoodsInfoPutway({ goodsId, goodsStatus })
        await this.getData()
      }
    })
  }
  putShelf = (goodsId, goodsStatus) => {
    React.$confirm({
      title: '您确定上架该商品吗？',
      onOk: async () => {
        await apiGetGoodsInfoPutway({ goodsId, goodsStatus })
        await this.getData()
      }
    })
  }
  openSkuDialog = (goodsId) => {
    this.setState({
      skuVisible: true,
      goodsId
    })
  }
  closeSkuDialog = () => {
    this.setState({
      skuVisible: false,
      goodsId: ''
    })
  }
  closeErrSyncDialog = () => {
    this.setState({
      ErrSyncVisible: false
    })
  }
  getSkuProperty = (skuPropertyArray, skuPropertyTable, skuType) => {
    let arr = [];
    if (skuPropertyTable.length > 0) {
      if (
        Object.prototype.toString.call(skuPropertyTable[0]) ===
        "[object Object]"
      ) {
        skuPropertyTable.forEach((v) => {
          arr.push(v);
        });
        arr = [arr];
      } else {
        arr = skuPropertyTable;
      }
    }
    this.setState({ skuPropertyArray, skuPropertyTable: arr, skuType });
  };
  /**
   * @desc 获取sku价格返回值
   * */
  getNumResult = (numResult) => {
    this.setState({ numResult });
  };
  handleOk = () => {
    const { numResult } = this.state
    let stockArr = numResult.map(v => {
      return {
        goodsId: v.goodsId,
        goodsSkuId: v.SKUId,
        skuStock: v.stock
      }
    })
    console.log(stockArr);
    this.updateStock(stockArr)
  }
  updateStock = async stockArr => {
    let res = await apiUpdateInventory([...stockArr])
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改成功'
      })
      this.closeSkuDialog()
    }
  }
  //表格导出
  async toExportTable() {
    this.setState({ down_loading: true })
    await getAllGoodsDetail().then(res => {
      if (res.code === 0 && res.data.length > 0) {
        let sheetSize = 1000,
          tH_data = [{ prop: 'goodsName', title: '商品名称' }, { prop: 'sku', title: '规格' }, { prop: 'originalPrice', title: '原价格(元)', valueType: 'number' }, { prop: 'currentPrice', title: '价格(元)', valueType: 'number' }],
          isSheet = true,
          fileName = '商品列表',
          tB_data = []
        res.data.forEach(item => {
          tB_data.push({
            goodsName: item.goodsName,
            sku: item.goodsKeyValue,
            originalPrice: (item.skuOriginalPrice / 100).toFixed(2),
            currentPrice: (item.skuCurrentPrice / 100).toFixed(2)
          })
          // if (item.hasOwnProperty('skuInfo') && item.skuInfo.length > 0)
          //   item.skuInfo.forEach(sku => {
          //     if (sku.hasOwnProperty('skuAttribute') && sku.skuAttribute.length > 0) {
          //       tB_data.push({
          //         goodsName: item.goodsName, currentPrice: (sku.skuCurrentPrice / 100).toFixed(2), originalPrice: (sku.skuOriginalPrice / 100).toFixed(2), sku: sku.skuAttribute.map(attr => {
          //           return `${attr.key}:${attr.value}`
          //         }).join(';')
          //       })
          //     }
          //   })
        })
        this.setState({ down_loading: false })
        exportSheetTable({ fileName, tH_data, tB_data, isSheet, sheetSize })

      } else {
        React.$message({
          type: 'warning',
          content: '导出操作失败,请重试'
        })
        this.setState({ down_loading: false })
      }
    }).catch(err => {
      React.$message({
        type: 'warning',
        content: '导出操作失败,请重试'
      })
      this.setState({ down_loading: false })

    })
  }
  render() {
    const {
      columns,
      dataSource,
      synchronousLoading,
      pageData: { pageNo, pageSize },
      total,
      loading,
      skuVisible,
      goodsId,
      synchronousVisible,
      options,
      down_loading,
      syncVisible,
      selectedRowKeys,
      ErrSyncVisible,
      syncfail,
      modalvisible,
      goods
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onChange,
      getCheckboxProps: (record) => {
        if (record.whetherSyn === 1) {
          return { disabled: true }
        } else {
          return null
        }
      }
    }

    return (
      <div className={"p-layout-box commodity-content"}>
        <SearchHeader toAdd={() => this.props.history.push('/mall/list/add')} history={this.props.history} getValue={this.getValue} toExport={() => this.toExportTable()} loading={down_loading}
          // toSync={()=>{this.pushSync()}}
          toStore={() => { this.pushSync() }} />
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={dataSource}
            loading={loading}
            rowKey={record => record.goodsId}
            rowSelection={rowSelection}
          />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
            pageSizeOptions={true}
          />
        </div>
        <TheDialog
          width={800}
          title={'修改库存'}
          visible={skuVisible}
          handleCancel={this.closeSkuDialog}
          handleOk={this.handleOk}
        >
          <SkuChange id={goodsId} getNumResult={this.getNumResult} getSkuProperty={this.getSkuProperty} />
        </TheDialog>
        <TheDialog
          width={400}
          title={'同步商品至商城'}
          visible={synchronousVisible}
          handleCancel={this.closeSynchronousDialog}
          // footer={true}
          handleOk={this.synchronousSave}
        >
          是否同步商品至商城商品列表？
          {/* <Form onFinish={this.synchronousSave}>
            <Form.Item label='品类' rules={[{ required: true }]} name='classId'>
              <Select options={options} placeholder="请选择商品品类" />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.closeSynchronousDialog}>取消</Button>
                  <Button loading={synchronousLoading} type="primary" htmlType="submit">确认</Button>
                </Space>
              </div>
            </Form.Item>
          </Form> */}
        </TheDialog>
        <TheDialog
          width={400}
          title={'批量同步商品至商城'}
          visible={syncVisible}
          handleCancel={this.closeSyncDialog}
          handleOk={this.syncSave}
        // footer={null}
        >
          是否同步商品至商城商品列表？
          {/* <Form onFinish={this.syncSave}>
            <Form.Item label='品类' rules={[{ required: true }]} name='classId'>
              <Select options={options} placeholder="请选择商品品类" />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.closeSyncDialog}>取消</Button>
                  <Button loading={synchronousLoading} type="primary" htmlType="submit">确认</Button>
                </Space>
              </div>
            </Form.Item>
          </Form> */}
        </TheDialog>
        <TheDialog
          width={400}
          title={'同步商品成功，以下商品已同步'}
          visible={ErrSyncVisible}
          handleCancel={this.closeErrSyncDialog}
          footer={null}
        >
          <List dataSource={syncfail} renderItem={(item) => (
            <List.Item>
              {item.title}
            </List.Item>)}
          />

        </TheDialog>
        <Modal visible={modalvisible}
          title={"警告！"}
          onCancel={this.onCancel}
          onOk={this.onOk}
        >
          <div>该商品正参与活动，是否继续修改商品？</div>
        </Modal>
      </div>
    );
  }
}

export default MallList;
